/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package rad.Java.Common.Class;

import java.sql.ResultSet;
import java.sql.SQLException;
import rad.Java.Common.DB.Database;
import rad.Java.Common.DB.GenerateSql;

/**
 *
 * @author rogerio
 */
public abstract class DefaultClass
{
        protected String _msg_erro;
        protected String _sql;
        protected GenerateSql _gsql;
        protected String _sequence;

        protected String _id;

        public DefaultClass()
        {
                _id  		= "";
                _sequence 	= "";
                _gsql = new GenerateSql();
        }

        public String getId()
        {
                return  _id; 
        }

        public void setId(String value)
        {
            this._id = value;
        }

        public String getErrorMessage()
        {
                return  _msg_erro;
        }


        public boolean execCommand(String _sql, boolean useTransaction)
        {
                Database.executeCommand(_sql, useTransaction);
                if( Database.Error )
                {
                        this._msg_erro = Database.ErrorMessage;
                        return false;
                }
                return true;
        }


        public String GetLastId()
        {
                if (Database.settings.getDatabaseProtocol().equals(Database.POSTGRESQL))
                    _sql = "SELECT last_value as id FROM " + _sequence;
                else if (Database.settings.getDatabaseProtocol().equals(Database.SQLITE))
                    _sql = "SELECT seq FROM sqlite_sequence WHERE name = '"+_gsql.getTable()+"'";
                else
                    _sql = "SELECT MAX("+getNameId()+") FROM "+_gsql.getTable();

               try
               {
                    return Database.executeScalar(_sql).toString();
               }
               catch(Exception e)
               {
                  return "0";
               }
        }

        public boolean get() throws SQLException {
            _gsql.prepare();
            _gsql.setValue("", "*");
            _gsql.setCommandType(GenerateSql.CommandType.CMD_SELECT);
            _gsql.setConditionalWhere(getNameId() + " = " + _id);
            if (_gsql.execute(true))
            {
                if (_gsql.next())
                {
                    get(_gsql.getResultSet());
                    return true;
                }
            }
            return false;
        }


        /// <summary>
        /// Save the current register in database
        /// </summary>
        ///<param name="useTransaction">Use transaction for store register</param>
        ///<returns>bool - true is register saved sucessful or false case not</returns>
        public boolean save()
        {
                return store(GenerateSql.CommandType.CMD_INSERT);
        }


        /// <summary>
        /// Update the current register in database
        /// </summary>
        ///<param name="useTransaction">Use transaction for update register</param>
        ///<returns>bool - true is register update sucessful or false case not</returns>
        public boolean update()
        {
                return store(GenerateSql.CommandType.CMD_UPDATE);
        }

        public boolean store()
        {
                if (_id.equals(""))
                        return store(GenerateSql.CommandType.CMD_INSERT);
                else
                        return store(GenerateSql.CommandType.CMD_UPDATE);
        }

        /// <summary>
        /// Store the class.
        /// </summary>
        /// <param name="ctype">CMD_UPDATE or CMD_INSERT</param>
        /// <returns>bool - true if the register was stored sucessful or false case not</returns>
        public boolean store(GenerateSql.CommandType ctype)
        {
                _gsql.prepare();
                _gsql.setCommandType(ctype);
                //Virtual method
                setGsql();

                if (ctype.equals(GenerateSql.CommandType.CMD_UPDATE))
                        _gsql.setConditionalWhere(getNameId() + " = "+_id);

                if (_gsql.execute(false))
                {
                        if (ctype == GenerateSql.CommandType.CMD_INSERT)
                                _id = GetLastId();
                        return true;
                }

                _msg_erro= _gsql.getMsgErro();
                return false;
        }

        /// <summary>
        /// Delete the currenty register seted in class
        /// </summary>
        /// <returns>bool - true is register deleted sucessful or false case not</returns>
        public boolean delete()
        {
                if (_id.equals(""))
                        return true;
                _gsql.prepare();
                _gsql.setCommandType(GenerateSql.CommandType.CMD_DELETE);
                _gsql.setConditionalWhere(getNameId()+ " = " +_id);

                if (_gsql.execute(false))
                        return true;
                _msg_erro= _gsql.getMsgErro();
                return false;
        }

        public native void setGsql();

        public native void get(ResultSet rs);

        public String getNameId()
        {
                String aux = "";
                if ( !_sequence.equals(""))
                {
                        //aux= _sequence.Remove(0,_sequence.IndexOf('_')+1);
                        aux= _sequence;
                        aux = aux.substring(_gsql.getTable().length()+1, aux.lastIndexOf('_'));                }
                return aux;
        }
}
